<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇的重点于理解 GMT 时间和本地时间的区别，掌握它们的换算方式，明白日期的多种格式，最后便是日期时间的几种小用例。">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第五章：Date">
<meta property="og:url" content="http://yoursite.com/2019/04/13/professional-javascript-chapter-5-Date/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇的重点于理解 GMT 时间和本地时间的区别，掌握它们的换算方式，明白日期的多种格式，最后便是日期时间的几种小用例。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/04/13/professional-javascript-chapter-5-Date/javascript.jpg">
<meta property="og:image" content="http://yoursite.com/2019/04/13/professional-javascript-chapter-5-Date/date-format.jpg">
<meta property="og:updated_time" content="2019-04-12T16:13:26.286Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第五章：Date">
<meta name="twitter:description" content="本篇的重点于理解 GMT 时间和本地时间的区别，掌握它们的换算方式，明白日期的多种格式，最后便是日期时间的几种小用例。">
<meta name="twitter:image" content="http://yoursite.com/2019/04/13/professional-javascript-chapter-5-Date/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/04/13/professional-javascript-chapter-5-Date/">





  <title>《JavaScript 高级程序设计》第五章：Date | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/04/13/professional-javascript-chapter-5-Date/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第五章：Date</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-04-13T07:18:09+08:00">
                2019-04-12
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2019/04/13/professional-javascript-chapter-5-Date/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇的重点于理解 <code>GMT</code> 时间和本地时间的区别，掌握它们的换算方式，明白日期的多种格式，最后便是日期时间的几种小用例。</blockquote>

<a id="more"></a>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>ECMAScript 中的 <code>Date</code> 类型是从早期 <code>Java</code> 的 <code>java.util.date</code> 类的基础上构建的，因此也采用了 UTC(Coordinated Universal Time, 国际协调时间) 的格式，以 1970年1月1日为基准点，保存之前或之后经过的时间戳（毫秒数）。 </p>
<p>使用 <code>new</code> 运算符结合 <code>Date()</code> 构造函数即可创建一个 <code>Date</code> 类型的实例对象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre></td></tr></table></figure>
<p>在 ECMAScript 中日期时间数据可以是一段字符串也可以是数值类型的时间戳，下面是一个字符串类型的日期时间数据的格式：</p>
<p><img src="/2019/04/13/professional-javascript-chapter-5-Date/date-format.jpg" alt="日期时间数据"></p>
<p><code>GMT</code> (格林威治时间，Green Wich Mean Time)，对比于 <code>UTC</code>，它们几乎是同一个概念，都是基于“格林威治标准时间”，只不过 <code>UTC</code> 的称呼更为正式，其次 <code>GMT</code> 更多的是天文学上的概念，既以本初子午线 “0度经线” 将每日太阳穿过的瞬间规定为正午时刻，然后以此制定时间，但是受限于地球自转的不均衡，其误差会越来越大。所以最终 <code>UTC</code> 继承自原有的以经线划分东西半球的基础，将地球再次划分为二十四时区，并使用原子钟来进行时间的测量，所以 <code>UTC</code> 于 <code>GMT</code> 在概念上是相同的，指的都是英国伦敦的本地时间（标准时）只是前者在时间测量上更为精准。</p>
<p><code>UTC</code> 时间将地球划分为二十四个时区，每个时区都有着自己的“本地时间”，而不同时区的本地时间若想进行交换，则需要借助于“时区信息”进行转换。</p>
<p>例如在中国向英国的一位友人发送一段时间信息：</p>
<pre><code>2019/01/19 23:00:00 GMT+0800
</code></pre><p>那么当英国的朋友接收到这条时间信息后，便能马上得出自己的时间，即在当地（英国）下午17点接收到来自你的这条信息，这就是因为本初子午线在英国，所以英国为0度时区，相比位于东八区的中国要差上八个小时，相同的换算要是放在美国就要复杂一些，因为美国国内就存在着不同的本地时间（美国当地时间）它们分别是，“夏令时”与“冬令时”，而中国只有一个“北京时间”。又因为中国处于东八区，所以时区信息上要加 <code>GMT + 0800</code> 进行标识。</p>
<p>在浏览器中调用 <code>new Date()</code> 创建的日期对象，其默认的日期时间值都是本地时间 —— 即非 <code>UTC</code> 时间。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>();             <span class="comment">//Sate Jan 19 2019 21:26:54 GMT+0800</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2019/01/19'</span>) <span class="comment">//Sat Jan 19 2019 00:00:00 GMT+0800 (中国标准时间)</span></span><br></pre></td></tr></table></figure>
<p>或者你也可以传入多个逗号隔开的表示年、月、日、时、分、秒的数值给 <code>Date()</code> 构造函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">2019</span>, <span class="number">0</span>, <span class="number">19</span>, <span class="number">21</span>, <span class="number">26</span>, <span class="number">0</span>); <span class="comment">//Sat Jan 19 2019 21:26:00 GMT+0800 (中国标准时间)</span></span><br></pre></td></tr></table></figure>
<p>需要注意的是，月份是从0开始，既0为1月。<br>使用 <code>Date()</code> 构造函数创建的日期时间都是本地时间，也就是非 <code>UTC</code> 时间，如果想创建一个 <code>UTC</code> 时间，则需要使用本地时间减去当前的时区时差。</p>
<p>好在关于当前时区的差值我们可以通过实例对象的 <code>getTimezoneOffset()</code> 方法来获取本地时间与 UTC 时间相差的分钟数，值为一个负数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line"><span class="keyword">var</span> utcDate = date * <span class="number">1</span> + date.getTimezoneOffset() * <span class="number">60</span> * <span class="number">1000</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(utcDate);</span><br></pre></td></tr></table></figure>
<blockquote>
<p>由此我们可以看出，UTC = 本地时间 - TimeZone(时区值)。</p>
</blockquote>
<p>最后，还有一点关于日期在年、月、日的分隔符上，国内常用是 <code>/</code> 与 <code>-</code>  两种分隔符号，但是实际上它们是有兼容性的，看下面的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2019/01/19'</span>); <span class="comment">//Sat Jan 19 2019 00:00:00 GMT+0800 (中国标准时间)</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2019-01-19'</span>); <span class="comment">//Sat Jan 19 2019 08:00:00 GMT+0800 (中国标准时间)</span></span><br></pre></td></tr></table></figure>
<p>从中我们可以看出使用 <code>/</code> 分隔符，并且缺省时间数据，系统默认创建的是以 <code>00:00:00</code> 为起点的 <code>GMT</code> 时间，而 <code>-</code> 分隔符则会在缺省时间段数据时，会以当前时区的时差值作为起始时间，还有就是在 <code>IE9-</code> 及以下的浏览器中会出现 <code>invild data</code> 或者直接抛出异常。因此 <code>\</code> 作为分隔符是我们推荐使用的。</p>
<h2 id="静态方法"><a href="#静态方法" class="headerlink" title="静态方法"></a>静态方法</h2><ul>
<li><strong>now()</strong></li>
</ul>
<p>返回当前系统日期时间的时间戳（毫秒数）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Date</span>.now(); <span class="comment">//1553699554229</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>UTC()</strong></li>
</ul>
<p>返回 <code>UTC</code> 时间 <code>1970/01/01 00:00:00</code> 到指定日期时间的时间戳，参数必须是表示年、月、日、时、分、秒的数值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Date</span>.UTC(<span class="number">2019</span>,<span class="number">0</span>,<span class="number">19</span>); <span class="comment">//1547856000000</span></span><br></pre></td></tr></table></figure>
<p>需要注意的是，<code>UTC()</code> 方法默认会对传入的小时值再加上当前时区的时差。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">1547856000000</span>); <span class="comment">//Sat Jan 19 2019 08:00:00 GMT+0800 (中国标准时间)</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>可以看到时间默认是8点。</p>
</blockquote>
<ul>
<li><strong>parse()</strong> </li>
</ul>
<p>用来专门解析字符串格式的日期时间值，其行为与 <code>UTC()</code> 方法类似，返回 <code>1970/01/01 00:00:00</code> 到指定日期时间的时间戳。<br>不同的是 <code>parse()</code> 方法不会像 <code>UTC()</code> 方法那样默认追加上当前时区的时差。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Date</span>.parse(<span class="string">'2019/01/19'</span>); <span class="comment">//1547827200000</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>(<span class="number">1547827200000</span>);<span class="comment">//Sat Jan 19 2019 00:00:00 GMT+0800 (中国标准时间)</span></span><br></pre></td></tr></table></figure>
<h2 id="实例方法"><a href="#实例方法" class="headerlink" title="实例方法"></a>实例方法</h2><p>实例方法指的是 <code>Date</code> 对象构造函数原型(prototype)上定义的方法，可以被其通过使用 <code>new</code> 运算符实例出来的对象所继承。</p>
<h2 id="转换方法"><a href="#转换方法" class="headerlink" title="转换方法"></a>转换方法</h2><p>“转换方法” 也是 <code>Date</code> 对象的“实例方法”，因为 <code>Date</code> 对象支持转换的日期/时间格式较多，所以这里就单独的列举出来说明。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法名</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">toString()</td>
<td style="text-align:left">返回带有时区信息国际通用格式的日期时间字符串。</td>
</tr>
<tr>
<td style="text-align:left">toLocaleString()</td>
<td style="text-align:left">返回符合本地格式的日期时间字符串</td>
</tr>
<tr>
<td style="text-align:left">valueOf()</td>
<td style="text-align:left">返回当前实例化对象的时间戳信息（数值）</td>
</tr>
<tr>
<td style="text-align:left">toDateString()</td>
<td style="text-align:left">返回通用格式带有周、月、日、年等信息的日期字符串</td>
</tr>
<tr>
<td style="text-align:left">toTimeString()</td>
<td style="text-align:left">返回通用格式带有时、分、秒、时区等信息的时间字符串</td>
</tr>
<tr>
<td style="text-align:left">toLocaleDateString()</td>
<td style="text-align:left">返回符合本地格式的包含年、月、日等信息的日期字符串</td>
</tr>
<tr>
<td style="text-align:left">toLocaleTimeString()</td>
<td style="text-align:left">返回符合本地格式的包含时、分、秒等信息的时间字符串</td>
</tr>
<tr>
<td style="text-align:left">toUTCString()</td>
<td style="text-align:left">返回符合 <code>UTC</code> 日期时间格式的字符串</td>
</tr>
<tr>
<td style="text-align:left">toISOString()</td>
<td style="text-align:left">返回符合 <code>ISO</code> 格式的日期时间字符串</td>
</tr>
<tr>
<td style="text-align:left">toJSON()</td>
<td style="text-align:left">返回符合 <code>JSON</code> 格式使用的日期时间字符串(使用 <code>toISOString()</code>)</td>
</tr>
</tbody>
</table>
<ul>
<li>本地格式</li>
</ul>
<p>当我们编写的应用不能确保在一个固定的地域中使用时，在日期时间的展示上最稳妥的方式莫非就是调用 <code>toLocaleString</code>、<code>toLocaleDateString</code>、<code>toLocaleTimeString</code> 等符合本地格式的日期时间转换方法。</p>
<p>当然，使用国际通用格式也是不错的解决方法。</p>
<ul>
<li><code>ISO</code> 日期时间格式</li>
</ul>
<p><code>ISO</code> 日期时间格式指的是符合 “国际标准化组织” 制定的 ISO 8601 日期和时间的表示方法，目前最新版本是第三版的 ISO8601:2004。具体格式如下所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"2019-03-28T15:09:38.151Z"</span></span><br></pre></td></tr></table></figure>
<p><code>ISO</code> 格式的日期和时间使用大写字母<code>T</code>作分隔，<code>T</code> 字符可以理解为占位符，在特殊的使用场景中可以被其它字符替换，例如 <code>GMT</code> 格式下就用空格代替，若时间段采用的是 <code>GMT</code> 时间则需要附加上一个大写字母 <code>Z</code>，当然也可以是具体的时区信息，例如：<code>+08</code>，时间段中秒与毫秒则用 “.” 点号符进行连接。</p>
<ul>
<li><code>JSON</code> 格式</li>
</ul>
<p><code>JSON</code> 数据中关于日期时间的值推荐采用的也是 ISO-8601 标准，既<code>YYYY-MM-DDTHH:mm:ss.sssZ</code> 格式。<br>需要注意的是 <code>toJSON()</code> 方法 IE8- 以下浏览器并不支持。</p>
<h2 id="日期-时间组件方法"><a href="#日期-时间组件方法" class="headerlink" title="日期/时间组件方法"></a>日期/时间组件方法</h2><p>“日期/时间组件方法” 也是 <code>Date</code> 对象的“实例方法”，这些方法都是 <code>Date</code> 对象最常用的也是最核心的方法。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法名</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">getTime()</td>
<td style="text-align:left">获取当前日期时间的时间戳（毫秒级）</td>
</tr>
<tr>
<td style="text-align:left">setTime()</td>
<td style="text-align:left">以毫秒数来更新当前日期时间对象的值</td>
</tr>
<tr>
<td style="text-align:left">getFullYear()</td>
<td style="text-align:left">获取4位数的年份</td>
</tr>
<tr>
<td style="text-align:left">setFullYear()</td>
<td style="text-align:left">设置年份</td>
</tr>
<tr>
<td style="text-align:left">getMonth()</td>
<td style="text-align:left">获取月份，取值范围（0~11）</td>
</tr>
<tr>
<td style="text-align:left">setMonth()</td>
<td style="text-align:left">设置月份，取值范围（0~11）</td>
</tr>
<tr>
<td style="text-align:left">getDate()</td>
<td style="text-align:left">获取天数，取值范围（1~31）</td>
</tr>
<tr>
<td style="text-align:left">setDate()</td>
<td style="text-align:left">设置日期对象的天数，取值范围（1~31）</td>
</tr>
<tr>
<td style="text-align:left">getDay()</td>
<td style="text-align:left">获取周，取值范围（0~6），0 表示周日，6表示周六</td>
</tr>
<tr>
<td style="text-align:left">getHours()</td>
<td style="text-align:left">获取小时，取值范围（0~23）</td>
</tr>
<tr>
<td style="text-align:left">setHours()</td>
<td style="text-align:left">设置小时，取值范围（0~23）</td>
</tr>
<tr>
<td style="text-align:left">getMinutes()</td>
<td style="text-align:left">获取分钟，取值范围（0~59）</td>
</tr>
<tr>
<td style="text-align:left">setMinutes()</td>
<td style="text-align:left">设置分钟，取值范围（0~59）</td>
</tr>
<tr>
<td style="text-align:left">getSeconds()</td>
<td style="text-align:left">获取秒数，取值范围（0~59）</td>
</tr>
<tr>
<td style="text-align:left">setSeconds()</td>
<td style="text-align:left">设置秒数，取值范围（0~59）</td>
</tr>
<tr>
<td style="text-align:left">getMilliseconds()</td>
<td style="text-align:left">获取毫秒数秒数，取值范围（0~1000）</td>
</tr>
<tr>
<td style="text-align:left">setMilliseconds()</td>
<td style="text-align:left">设置毫秒数秒数，取值范围（0~1000）</td>
</tr>
<tr>
<td style="text-align:left">getTimezoneOffset()</td>
<td style="text-align:left">返回当前时区与世界统一协调时之间相差的分钟数。</td>
</tr>
</tbody>
</table>
<blockquote>
<p>同样的，相同的方法对于 <code>UTC</code> 时间都有另一套实现，格式是：<code>getUTC***</code> 或者 <code>setUTC***</code>。</p>
</blockquote>
<h2 id="应用示例"><a href="#应用示例" class="headerlink" title="应用示例"></a>应用示例</h2><ul>
<li>获取时间戳</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line"></span><br><span class="line"><span class="built_in">Date</span>.now();</span><br><span class="line"></span><br><span class="line">+ date;</span><br><span class="line">date * <span class="number">1</span>;</span><br><span class="line">date.valueOf();</span><br><span class="line">date.getTime();</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>* date</code> 与 <code>date * 1</code> 涉及到了对象的隐式转换问题。</p>
</blockquote>
<ul>
<li>耗时分析</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> start = <span class="built_in">Date</span>.now();</span><br><span class="line"></span><br><span class="line"><span class="comment">// doSomething...</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Date</span>.now() - start;</span><br></pre></td></tr></table></figure>
<ul>
<li>时间戳快速格式化</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2019/01/20 13:40:00'</span>);</span><br><span class="line"><span class="keyword">var</span> timeStamp = (<span class="built_in">Date</span>.now() - date * <span class="number">1</span>) / <span class="number">1000</span>; <span class="comment">// Convert Seconds</span></span><br><span class="line"></span><br><span class="line">timeStamp / <span class="number">3600</span>; <span class="comment">// Hours</span></span><br><span class="line">timeStamp % <span class="number">3600</span> / <span class="number">60</span>; <span class="comment">// Minutes</span></span><br><span class="line">timeStamp % <span class="number">3600</span> % <span class="number">60</span>; <span class="comment">//Seconds</span></span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/11/professional-javascript-chapter-5-RegExp/" rel="next" title="《JavaScript 高级程序设计》第五章：RegExp">
                <i class="fa fa-chevron-left"></i> 《JavaScript 高级程序设计》第五章：RegExp
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/17/professional-javascript-chapter-5-basic-packaging/" rel="prev" title="《JavaScript 高级程序设计》第五章：基本包装类型">
                《JavaScript 高级程序设计》第五章：基本包装类型 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#静态方法"><span class="nav-number">2.</span> <span class="nav-text">静态方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例方法"><span class="nav-number">3.</span> <span class="nav-text">实例方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#转换方法"><span class="nav-number">4.</span> <span class="nav-text">转换方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#日期-时间组件方法"><span class="nav-number">5.</span> <span class="nav-text">日期/时间组件方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#应用示例"><span class="nav-number">6.</span> <span class="nav-text">应用示例</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
